package com.example.news.service.impl;

import com.example.news.mapper.BookMapper;
import com.example.news.pojo.*;
import com.example.news.service.BookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    private Integer pageSize = 3;

    @Override
    public PageResult<Book> getAllBooks(Integer currentPage, Integer publisherId) {
        PageHelper.startPage(currentPage,pageSize);
        //查询数据集合（但不是在这里真实执行的）
        List<Book> bookList = bookMapper.getAllBooks(currentPage, publisherId);
        //这里真实执行sql获得数据集合
        PageInfo<Book> pageInfo = new PageInfo<>(bookList);
        //封装返回结果对象
        PageResult<Book> pageResult = new PageResult<>();
        pageResult.setCurrentPage(currentPage);
        pageResult.setPageSize(pageSize);
        pageResult.setTotalCount((int)pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setResultList(pageInfo.getList());
        return pageResult;
    }

    @Override
    public List<Publisher> getAllPublisher() {
        return bookMapper.getAllPublisher();
    }

    @Override
    public List<Category> getAllCategory() {
        return bookMapper.getAllCategory();
    }

    @Override
    @Transactional
    public Integer addBook(Book book, List<Integer> categoryIdList) {
        if(bookMapper.addBookInfo(book) == 0){
            return 0;
        }
        if(bookMapper.addBookRelationInfo(book.getBookId(),categoryIdList) == 0){
            return 0;
        }
        return 1;
    }

    @Override
    public Integer addBookRelationInfo(Integer bookId, List<Integer> categoryIdList) {
        return bookMapper.addBookRelationInfo(bookId, categoryIdList);
    }

    @Override
    public Book findBookById(Integer bookId) {
        return bookMapper.findBookById(bookId);
    }

    @Override
    public Integer delBookRelationInfo(Integer bookId) {
        return bookMapper.delBookRelationInfo(bookId);
    }

    @Override
    public Integer updateBookInfo(Book book) {
        return bookMapper.updateBookInfo(book);
    }
}
